import { useTranslation } from 'react-i18next'
import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { MessageType } from '@/types'
import useMessage from '@/hooks/useMessage'
import {
  Button,
  Dialog, DialogContent, DialogActions,
  FormControl,
  TextField,
} from '@mui/material'

let externalSetDialogOpen: (state: boolean) => void = () => {}
let externalsetMessage: (message: MessageType) => void = () => {}

const EditMessageDialog: React.FC = () => {
  const { t } = useTranslation()
  const [open, setOpen] = useState(false)
  const [message, setMessage] = useState<MessageType | null>(null)
  const { updateMessage } = useMessage()

  useEffect(() => {
    externalSetDialogOpen = setOpen
    externalsetMessage = setMessage
  })

  const onSave = () => {
    if (message) {
      updateMessage(message)
    }
    setOpen(false)
  }

  if (!open) return null

  return createPortal(
    <Dialog
      open={!!message}
      onClose={() => setOpen(false)}
      fullWidth
    >
      <DialogContent>
        {
          message && (
            <FormControl fullWidth>
              <TextField
                minRows={6}
                maxRows={15}
                multiline
                value={message.content}
                onChange={e => setMessage({ ...message, content: e.target.value })}
              />
            </FormControl>
          )
        }
      </DialogContent>
      <DialogActions>
        <Button onClick={() => setOpen(false)}>{t('dialog cancel btn')}</Button>
        <Button onClick={onSave}>{t('dialog ok btn')}</Button>
      </DialogActions>
    </Dialog>,
    document.body,
  )
}

export const showEditMessageDialog = (message: MessageType) => {
  externalSetDialogOpen(true)
  externalsetMessage(message)
}

export const hideEditMessageDialog = () => {
  externalSetDialogOpen(false)
}

export default EditMessageDialog
